#include "include/connect.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

int Connect::createConnect() {
  sfd = socket(this->protofamily, this->type, this->protocol);
  if (sfd <= 0)
    perror("createConnect is error: ");
  return sfd;
};

int Connect::createConnect(int protofamily, int type, int protocol, int port){
    this->protofamily = protofamily;
    this->type = type;
    this->protocol = protocol;

    sfd = socket(this->protofamily, this->type, this->protocol);
    if(sfd <= 0)
        perror("createConnect is error: ");
    return sfd;
};

int Connect::listenClient(){
    // 自动获取本机IP，监听端口
    addrInfo = (struct sockaddr_in*)malloc(sizeof(&addrInfo));
    addrInfo->sin_family = protofamily;
    addrInfo->sin_addr.s_addr = htonl(INADDR_ANY);
    addrInfo->sin_port = htons(port);

    int flag = bind(sfd, (struct sockaddr*)addrInfo, sizeof(*addrInfo));
    if(flag != 0){
        perror("bind is error: ");
        return -1;
    }

    cout << "listening client....\n";
    flag = listen(sfd, MAX_NUM);
    if(flag != 0)
        perror("listen is error: ");

    unsigned int length = sizeof(*addrInfo);
    flag = accept(sfd, (struct sockaddr*)addrInfo, &length);
    if(flag == -1)
        perror("accept is error: ");
    return 0;
};

int Connect::clientConnect(const char* ip, int port){
    int flag = -1;
    addrInfo = (struct sockaddr_in*)malloc(sizeof(&addrInfo));
    addrInfo->sin_family = protofamily;
    addrInfo->sin_port= htons(port);
    flag = inet_pton( protofamily, ip, &(addrInfo->sin_addr));

    flag = connect(sfd, (struct sockaddr*)addrInfo, sizeof(*addrInfo));
    if(flag != 0)
        perror("client connect is error: ");
    return 0;
};

int Connect::closeConn(){
    free(addrInfo);
    close(sfd);
    return 0;
};

